package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.Event;
import com.example.ercmssystem2.entity.EventType;
import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.service.EventService;
import com.example.ercmssystem2.service.UserService;
import com.example.ercmssystem2.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/events")
@CrossOrigin(origins = "*")
public class EventController {

    private final EventService eventService;
    private final UserService userService;
    private final com.example.ercmssystem2.service.EventTypeService eventTypeService;
    private final JwtUtil jwtUtil;

    @Autowired
    public EventController(EventService eventService, UserService userService, 
                          com.example.ercmssystem2.service.EventTypeService eventTypeService,
                          JwtUtil jwtUtil) {
        this.eventService = eventService;
        this.userService = userService;
        this.eventTypeService = eventTypeService;
        this.jwtUtil = jwtUtil;
    }

    // 从JWT token中获取当前用户ID
    private Long getCurrentUserId(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return null;
        }
        
        try {
            String token = authHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                String username = jwtUtil.extractUsername(token);
                User user = userService.findByUsername(username);
                return user != null ? user.getId() : null;
            }
        } catch (Exception e) {
            // Token无效或解析失败
        }
        
        return null;
    }
    
    // 检查用户是否为管理员
    private boolean isAdmin(User user) {
        return user != null && "ADMIN".equals(user.getRole());
    }
    
    // 检查用户是否为调度员
    private boolean isDispatcher(User user) {
        return user != null && "DISPATCHER".equals(user.getRole());
    }
    
    // 检查用户是否为部门经理
    private boolean isDeptManager(User user) {
        return user != null && "DEPT_MANAGER".equals(user.getRole());
    }

    @GetMapping
    public Map<String, Object> getAllEvents(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String priority,
            @RequestParam(required = false) String severity,
            @RequestParam(required = false) Long eventType,
            @RequestParam(required = false) Long handler
    ) {
        List<Event> events = eventService.findAllEvents();
        if (status != null && !status.isEmpty()) {
            events = events.stream().filter(e -> status.equals(e.getStatus())).toList();
        }
        if (priority != null && !priority.isEmpty()) {
            events = events.stream().filter(e -> priority.equals(e.getPriority())).toList();
        }
        if (severity != null && !severity.isEmpty()) {
            events = events.stream().filter(e -> severity.equals(e.getSeverity())).toList();
        }
        if (eventType != null) {
            events = events.stream().filter(e -> e.getEventType() != null && eventType.equals(e.getEventType().getId())).toList();
        }
        if (handler != null) {
            events = events.stream().filter(e -> e.getHandler() != null && handler.equals(e.getHandler().getId())).toList();
        }
        Map<String, Object> resp = new HashMap<>();
        resp.put("success", true);
        resp.put("data", events);
        return resp;
    }

    @GetMapping("/{id}")
    public ResponseEntity<Event> getEventById(@PathVariable Long id) {
        Event event = eventService.findById(id);
        if (event != null) {
            return ResponseEntity.ok(event);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping
    public ResponseEntity<?> createEvent(@RequestBody Event event, 
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            if (currentUserId != null) {
                event.setCreatedBy(currentUserId);
            }
            
            // 确保必要字段有默认值
            if (event.getStatus() == null) {
                event.setStatus("PENDING");
            }
            if (event.getPriority() == null) {
                event.setPriority("MEDIUM");
            }
            if (event.getSeverity() == null) {
                event.setSeverity("MODERATE");
            }
            if (event.getStartTime() == null) {
                event.setStartTime(LocalDateTime.now());
            }
            
            Event savedEvent = eventService.saveEvent(event);
            return ResponseEntity.status(HttpStatus.CREATED).body(savedEvent);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("error", "创建事件失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<Event> updateEvent(@PathVariable Long id, @RequestBody Event event) {
        Event existingEvent = eventService.findById(id);
        if (existingEvent != null) {
            event.setId(id);
            return ResponseEntity.ok(eventService.saveEvent(event));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteEvent(@PathVariable Long id,
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        // 权限验证
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "未登录"));
        }
        
        // 获取当前用户信息
        User currentUser = userService.findById(currentUserId);
        if (currentUser == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(Map.of("success", false, "message", "用户不存在"));
        }
        
        // 检查权限：只有管理员、调度员和部门经理可以删除事件
        if (!isAdmin(currentUser) && !isDispatcher(currentUser) && !isDeptManager(currentUser)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(Map.of("success", false, "message", "您没有权限删除事件"));
        }
        
        // 如果是部门经理，检查事件是否属于其部门
        if (isDeptManager(currentUser)) {
            Event event = eventService.findById(id);
            if (event == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Map.of("success", false, "message", "事件不存在"));
            }
            
            // 检查事件是否属于当前用户管理的部门（通过处理人）
            if (event.getHandler() != null && event.getHandler().getDepartmentId() != null) {
                if (!event.getHandler().getDepartmentId().equals(currentUser.getDepartmentId())) {
                    return ResponseEntity.status(HttpStatus.FORBIDDEN)
                        .body(Map.of("success", false, "message", "您只能删除本部门处理的事件"));
                }
            } else {
                // 如果事件没有处理人或处理人没有部门，部门经理不能删除
                return ResponseEntity.status(HttpStatus.FORBIDDEN)
                    .body(Map.of("success", false, "message", "您只能删除本部门处理的事件"));
            }
        }
        
        try {
            eventService.deleteEvent(id);
            return ResponseEntity.ok(Map.of("success", true, "message", "事件删除成功"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("success", false, "message", "删除事件失败: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}/status/{status}")
    public ResponseEntity<Event> updateEventStatus(@PathVariable Long id, @PathVariable String status) {
        Event updatedEvent = eventService.updateEventStatus(id, status);
        if (updatedEvent != null) {
            return ResponseEntity.ok(updatedEvent);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<Event>> getEventsByStatus(@PathVariable String status) {
        return ResponseEntity.ok(eventService.findByStatus(status));
    }

    // 终端用户操作相关API
    @PostMapping("/{id}/accept")
    public ResponseEntity<Event> acceptEvent(@PathVariable Long id,
                                           @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            Event event = eventService.acceptEvent(id, currentUserId);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/en-route")
    public ResponseEntity<Event> startEnRoute(@PathVariable Long id, @RequestBody Map<String, Object> request,
                                            @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Double latitude = (Double) request.get("latitude");
        Double longitude = (Double) request.get("longitude");
        
        try {
            Event event = eventService.startEnRoute(id, currentUserId, latitude, longitude);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/arrive")
    public ResponseEntity<Event> arriveAtScene(@PathVariable Long id, @RequestBody Map<String, Object> request,
                                             @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Double latitude = (Double) request.get("latitude");
        Double longitude = (Double) request.get("longitude");
        
        try {
            Event event = eventService.arriveAtScene(id, currentUserId, latitude, longitude);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/start-processing")
    public ResponseEntity<Event> startProcessing(@PathVariable Long id,
                                               @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            Event event = eventService.startProcessing(id, currentUserId);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/complete")
    public ResponseEntity<Event> completeEvent(@PathVariable Long id, @RequestBody Map<String, String> request,
                                             @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        String completionNotes = request.get("completionNotes");
        try {
            Event event = eventService.completeEvent(id, currentUserId, completionNotes);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/return")
    public ResponseEntity<Event> startReturning(@PathVariable Long id,
                                              @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            Event event = eventService.startReturning(id, currentUserId);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/update-location")
    public ResponseEntity<Event> updateLocation(@PathVariable Long id, @RequestBody Map<String, Object> request,
                                              @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Double latitude = (Double) request.get("latitude");
        Double longitude = (Double) request.get("longitude");
        
        try {
            Event event = eventService.updateLocation(id, currentUserId, latitude, longitude);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/safety-status")
    public ResponseEntity<Event> updateSafetyStatus(@PathVariable Long id, @RequestBody Map<String, String> request,
                                                   @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        String status = request.get("status");
        try {
            Event event = eventService.updateSafetyStatus(id, currentUserId, status);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/request-support")
    public ResponseEntity<Event> requestSupport(@PathVariable Long id, @RequestBody Map<String, String> request,
                                              @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        String supportType = request.get("supportType");
        String description = request.get("description");
        try {
            Event event = eventService.requestSupport(id, currentUserId, supportType, description);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/cancel-support")
    public ResponseEntity<Event> cancelSupportRequest(@PathVariable Long id,
                                                    @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            Event event = eventService.cancelSupportRequest(id, currentUserId);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/sos")
    public ResponseEntity<Event> sendSOS(@PathVariable Long id, @RequestBody Map<String, String> request,
                                       @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        String message = request.get("message");
        try {
            Event event = eventService.sendSOS(id, currentUserId, message);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 查询相关API
    @GetMapping("/my-events")
    public ResponseEntity<List<Event>> getMyEvents(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(eventService.getUserEvents(currentUserId));
    }

    @GetMapping("/my-active-events")
    public ResponseEntity<List<Event>> getMyActiveEvents(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        return ResponseEntity.ok(eventService.getUserActiveEvents(currentUserId));
    }

    @GetMapping("/my-current-event")
    public ResponseEntity<Event> getMyCurrentEvent(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Optional<Event> event = eventService.getCurrentActiveEvent(currentUserId);
        return event.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/needing-attention")
    public ResponseEntity<List<Event>> getEventsNeedingAttention() {
        List<Event> events = eventService.getEventsNeedingAttention();
        return ResponseEntity.ok(events);
    }

    @GetMapping("/overdue")
    public ResponseEntity<List<Event>> getOverdueEvents() {
        List<Event> events = eventService.getOverdueEvents();
        return ResponseEntity.ok(events);
    }

    // 统计相关API
    @GetMapping("/my-statistics")
    public ResponseEntity<Map<String, Object>> getMyStatistics(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Map<String, Object> stats = eventService.getUserEventStatistics(currentUserId);
        return ResponseEntity.ok(stats);
    }

    @GetMapping("/{id}/performance")
    public ResponseEntity<Map<String, Object>> getEventPerformance(@PathVariable Long id) {
        try {
            Map<String, Object> stats = eventService.getEventPerformanceStatistics(id);
            return ResponseEntity.ok(stats);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/{id}/timeline")
    public ResponseEntity<List<Map<String, Object>>> getEventTimeline(@PathVariable Long id) {
        try {
            List<Map<String, Object>> timeline = eventService.getEventTimeline(id);
            return ResponseEntity.ok(timeline);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/{id}/response-stats")
    public ResponseEntity<Map<String, Object>> getEventResponseStats(@PathVariable Long id) {
        try {
            Map<String, Object> stats = eventService.getEventResponseStatistics(id);
            return ResponseEntity.ok(stats);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    // 管理相关API
    @PostMapping("/{id}/reassign")
    public ResponseEntity<Event> reassignEvent(@PathVariable Long id, @RequestBody Map<String, Object> request,
                                             @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        Long newResponderId = Long.valueOf(request.get("newResponderId").toString());
        String reason = (String) request.get("reason");
        
        try {
            Event event = eventService.reassignEvent(id, newResponderId, reason);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/{id}/escalate")
    public ResponseEntity<Event> escalateEvent(@PathVariable Long id, @RequestBody Map<String, String> request,
                                             @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        String escalationReason = request.get("escalationReason");
        try {
            Event event = eventService.escalateEvent(id, escalationReason);
            return ResponseEntity.ok(event);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/batch-update-status")
    public ResponseEntity<List<Event>> batchUpdateStatus(@RequestBody Map<String, Object> request,
                                                        @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        @SuppressWarnings("unchecked")
        List<Long> eventIds = (List<Long>) request.get("eventIds");
        String status = (String) request.get("status");
        
        try {
            List<Event> updatedEvents = eventService.batchUpdateStatus(eventIds, status);
            return ResponseEntity.ok(updatedEvents);
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 历史查询API
    @GetMapping("/my-history")
    public ResponseEntity<List<Event>> getMyEventHistory(@RequestParam(required = false) String start, 
                                                        @RequestParam(required = false) String end,
                                                        @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        LocalDateTime startTime = start != null ? LocalDateTime.parse(start) : LocalDateTime.now().minusDays(30);
        LocalDateTime endTime = end != null ? LocalDateTime.parse(end) : LocalDateTime.now();
        
        List<Event> events = eventService.getEventHistory(currentUserId, startTime, endTime);
        return ResponseEntity.ok(events);
    }

    // 获取用户历史任务
    @GetMapping("/my-completed-events")
    public ResponseEntity<List<Event>> getMyCompletedEvents(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        List<Event> completedEvents = eventService.getUserCompletedEvents(currentUserId);
        return ResponseEntity.ok(completedEvents);
    }

    // 获取用户今日完成任务
    @GetMapping("/my-today-completed-events")
    public ResponseEntity<List<Event>> getMyTodayCompletedEvents(@RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        List<Event> todayCompletedEvents = eventService.getUserTodayCompletedEvents(currentUserId);
        return ResponseEntity.ok(todayCompletedEvents);
    }

    // 导出API
    @GetMapping("/{id}/export")
    public ResponseEntity<byte[]> exportEventReport(@PathVariable Long id) {
        try {
            byte[] report = eventService.exportEventReport(id);
            return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"event-report-" + id + ".pdf\"")
                .body(report);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/my-history/export")
    public ResponseEntity<byte[]> exportMyEventHistory(@RequestParam(required = false) String start, 
                                                      @RequestParam(required = false) String end,
                                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        LocalDateTime startTime = start != null ? LocalDateTime.parse(start) : LocalDateTime.now().minusDays(30);
        LocalDateTime endTime = end != null ? LocalDateTime.parse(end) : LocalDateTime.now();
        
        try {
            byte[] report = eventService.exportUserEventHistory(currentUserId, startTime, endTime);
            return ResponseEntity.ok()
                .header("Content-Disposition", "attachment; filename=\"my-event-history.pdf\"")
                .body(report);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/{id}/coordinates-status")
    public ResponseEntity<Map<String, Object>> getCoordinatesStatus(@PathVariable Long id) {
        try {
            boolean hasValidCoordinates = eventService.hasValidCoordinates(id);
            Event event = eventService.findById(id);
            
            Map<String, Object> result = new HashMap<>();
            result.put("hasValidCoordinates", hasValidCoordinates);
            result.put("latitude", event != null ? event.getCurrentLatitude() : null);
            result.put("longitude", event != null ? event.getCurrentLongitude() : null);
            result.put("lastLocationUpdate", event != null ? event.getLastLocationUpdate() : null);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(Map.of("error", "获取坐标状态失败: " + e.getMessage()));
        }
    }

    // 获取事件类型列表
    @GetMapping("/event-types")
    public Map<String, Object> getEventTypes() {
        List<EventType> types = eventTypeService.findAllEventTypes();
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", types);
        return response;
    }

    // 获取事件统计数据
    @GetMapping("/statistics")
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalEvents", eventService.findAllEvents().size());
        stats.put("pendingEvents", eventService.findByStatus("PENDING").size());
        stats.put("inProgressEvents", eventService.findByStatus("IN_PROGRESS").size());
        stats.put("resolvedEvents", eventService.findByStatus("RESOLVED").size());
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", stats);
        return response;
    }

    // 创建新事件类型
    @PostMapping("/event-types")
    public Map<String, Object> createEventType(@RequestBody Map<String, String> req,
                                             @RequestHeader(value = "Authorization", required = false) String authHeader) {
        // 检查用户权限
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("success", false);
            resp.put("message", "未登录");
            return resp;
        }
        
        String name = req.get("name");
        String description = req.getOrDefault("description", "");
        Map<String, Object> resp = new HashMap<>();
        if (name == null || name.trim().isEmpty()) {
            resp.put("success", false);
            resp.put("message", "事件类型名称不能为空");
            return resp;
        }
        if (eventTypeService.findByName(name) != null) {
            resp.put("success", false);
            resp.put("message", "事件类型已存在");
            return resp;
        }
        EventType type = new EventType();
        type.setName(name);
        type.setDescription(description);
        type.setEnabled(true);
        type.setCreatedAt(java.time.LocalDateTime.now());
        type.setUpdatedAt(java.time.LocalDateTime.now());
        eventTypeService.saveEventType(type);
        resp.put("success", true);
        resp.put("data", type);
        return resp;
    }

    @GetMapping("/{id}/latest-responder-location")
    public ResponseEntity<Map<String, Object>> getLatestResponderLocation(@PathVariable Long id,
                                                                        @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            String location = eventService.getLatestResponderLocation(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", location);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取响应者位置失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    @GetMapping("/{id}/all-responder-locations")
    public ResponseEntity<Map<String, Object>> getAllResponderLocations(@PathVariable Long id,
                                                                      @RequestHeader(value = "Authorization", required = false) String authHeader) {
        Long currentUserId = getCurrentUserId(authHeader);
        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        
        try {
            List<Map<String, Object>> locations = eventService.getAllResponderLocations(id);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", locations);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取所有响应者位置失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
} 